<?php

namespace app\admin\controller\finance;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Config;
use think\Db;

/**
 * 资金概况
 * @icon fa fa-circle-o
 */
class Home extends Backend
{
    public function index()
    {
        $group = $this->auth->getGroups();
        $groupId = $group[0]["group_id"];
        $this->view->assign("groupId", $groupId);
        if ($this->request->isPost()) {
            //选择时间重新查询图表统计
            $date = $this->request->post('date', '');
            $totalChart = $this->totalChart($date);
            $this->success('', '', $totalChart);
        }

        //数量统计
        $totalNumber = $this->totalNumber();
        $this->view->assign("totalNumber", $totalNumber);

        //图表统计
        $totalChart = $this->totalChart();
        $this->view->assign("totalChart", $totalChart);
        $this->assignconfig('totalChart', $totalChart);

        return $this->view->fetch();
    }

    //数量统计
    private function totalNumber()
    {
        $admin = $this->auth->getUserInfo();
        $group = $this->auth->getGroups();
        $groupId = $group[0]["group_id"];
        if ($groupId == 1) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'unaudited'])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'unaudited'])->sum('amount');
        } else if ($groupId == 2) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'unaudited'])->where(['h_id' => $admin["home_id"]])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'unaudited'])->where(['h_id' => $admin["home_id"]])->sum('amount');
        } else if ($groupId == 3) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'unaudited'])->where(['u_id' => $admin["id"]])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'unaudited'])->where(['u_id' => $admin["id"]])->sum('amount');
        }
        //未审核总收入
        $result[] = [
            'icon_color' => '#444C69',
            'is_money' => 1,
            'total' => $income,
            'lastTotal' => 0,
            'ratio' => 0, //不等于0页面上才会显示
            'title' => '未审核总收入',
            'icon' => 'fa fa-sign-in',
            'subtitle' => '全部'
        ];
        //未审核总支出
        $result[] = [
            'icon_color' => '#F39C12',
            'is_money' => 1,
            'total' => $spending,
            'lastTotal' => 0,
            'ratio' => 0,
            'title' => '未审核总支出',
            'icon' => 'fa fa-sign-out',
            'subtitle' => '全部'
        ];

        //实时余额
        if ($groupId == 1) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->sum('amount');
        } else if ($groupId == 2) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->where(['h_id' => $admin["home_id"]])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->where(['h_id' => $admin["home_id"]])->sum('amount');
        } else if ($groupId == 3) {
            $income = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->where(['u_id' => $admin["id"]])->sum('amount');
            $spending = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->where(['u_id' => $admin["id"]])->sum('amount');
        }
        $result[] = [
            'icon_color' => '#00ccff',
            'is_money' => 1,
            'total' => $income - $spending,
            'lastTotal' => 0,
            'ratio' => 0,
            'title' => '实时余额',
            'icon' => 'fa fa-rmb',
            'subtitle' => '全部'
        ];
        //总流入
        $result[] = [
            'icon_color' => '#446af5',
            'is_money' => 1,
            'total' => $income,
            'lastTotal' => 0,
            'ratio' => 0, //不等于0页面上才会显示
            'title' => '总收入',
            'icon' => 'fa fa-sign-in',
            'subtitle' => '全部'
        ];
        //总流出
        $result[] = [
            'icon_color' => '#cc6b6b',
            'is_money' => 1,
            'total' => $spending,
            'lastTotal' => 0,
            'ratio' => 0,
            'title' => '总支出',
            'icon' => 'fa fa-sign-out',
            'subtitle' => '全部'
        ];

        //本月收入
        if ($groupId == 1) {
            $total = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'month')->sum('amount');
            $lastTotal = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->sum('amount');
        } else if ($groupId == 2) {
            $total = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['h_id' => $admin["home_id"]])->sum('amount');
            $lastTotal = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->where(['h_id' => $admin["home_id"]])->sum('amount');
        } else if ($groupId == 3) {
            $total = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['u_id' => $admin["id"]])->sum('amount');
            $lastTotal = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->where(['u_id' => $admin["id"]])->sum('amount');
        }

        $ratio = $lastTotal > 0 ? ceil((($total - $lastTotal) / $lastTotal) * 100) : ($total > 0 ? 100 : 0);
        $result[] = [
            'icon_color' => '#09a31e',
            'is_money' => 1,
            'total' => $total,
            'lastTotal' => $lastTotal,
            'ratio' => $ratio,
            'title' => '本月收入',
            'icon' => 'fa fa-calendar-plus-o',
            'subtitle' => '本月'
        ];

        //本月支出
        if ($groupId == 1) {
            $total = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'month')->sum('amount');
            $lastTotal = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->sum('amount');
        } else if ($groupId == 2) {
            $total = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['h_id' => $admin["home_id"]])->sum('amount');
            $lastTotal = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->where(['h_id' => $admin["home_id"]])->sum('amount');
        } else if ($groupId == 3) {
            $total = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['u_id' => $admin["id"]])->sum('amount');
            $lastTotal = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'last month')->where(['u_id' => $admin["id"]])->sum('amount');
        }



        $ratio = $lastTotal > 0 ? ceil((($total - $lastTotal) / $lastTotal) * 100) : ($total > 0 ? 100 : 0);
        $result[] = [
            'icon_color' => '#f32792',
            'is_money' => 1,
            'total' => $total,
            'lastTotal' => $lastTotal,
            'ratio' => $ratio,
            'title' => '本月支出',
            'icon' => 'fa fa-calendar-minus-o',
            'subtitle' => '本月'
        ];
        return $result;
    }

    //图表统计
    private function totalChart($date = '')
    {
        if ($date) {
            list($start, $end) = explode(' - ', $date);
            $starttime = strtotime($start);
            $endtime = strtotime($end);
        } else {
            $starttime = \fast\Date::unixtime('day', -29, 'begin');
            $endtime = \fast\Date::unixtime('day', 0, 'end');
        }
        $result = [];

        //判断统计时间格式，年月，年月日，时分
        $totalseconds = $endtime - $starttime;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }

        $result[] = $this->incomesAndPending($endtime, $starttime, $totalseconds, $format);
        $result[] = $this->incomesAndPendingPie($endtime, $starttime, $format);
        // $result[] = $this->groupchart($endtime, $starttime, $format);
        // $result[] = $this->groupchartOut($endtime, $starttime, $format);
        return $result;
    }


    //部门收入饼状图
    private function groupchart($endtime, $starttime, $format)
    {
        //通用sql
        $sql = 'SUM(amount) AS amount,DATE_FORMAT(FROM_UNIXTIME(datatime), "' . $format . '") AS field_time';
        $category = [];
        $data = [];
        $groupList = collection(AuthGroup::field('id,name')->select())->toArray();
        foreach ($groupList as $val) {
            $amount = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->where('group_id', '=', $val['id'])
                ->field("{$sql}")->sum('amount');
            $category[] = $val['name'];
            $data[] = [
                'value' => $amount,
                'name' => $val['name']
            ];
        }
        //组装数据
        $result = [
            'category' => $category,
            'data' => $data,
            'id' => '3',
            'legend_title' => '收入',
            'unit' => '元',
            'chart_type' => 'pie',
            'title' => '部门收入',
            'subtext' => '所有部门收入对比'
        ];
        return $result;
    }

    //部门支出饼状图
    private function groupchartOut($endtime, $starttime, $format)
    {






        //通用sql
        $sql = 'SUM(amount) AS amount,DATE_FORMAT(FROM_UNIXTIME(datatime), "' . $format . '") AS field_time';
        $category = [];
        $data = [];
        $groupList = collection(AuthGroup::field('id,name')->select())->toArray();
        foreach ($groupList as $val) {
            $amount = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->where('group_id', '=', $val['id'])
                ->field("{$sql}")->sum('amount');
            $category[] = $val['name'];
            $data[] = [
                'value' => $amount,
                'name' => $val['name']
            ];
        }
        //组装数据
        $result = [
            'category' => $category,
            'data' => $data,
            'id' => '4',
            'legend_title' => '支出',
            'unit' => '元',
            'chart_type' => 'pie',
            'title' => '部门支出',
            'subtext' => '所有部门支出对比'
        ];
        return $result;
    }

    //收入与支出饼状图
    private function incomesAndPendingPie($endtime, $starttime, $format)
    {

        $admin = $this->auth->getUserInfo();
        $group = $this->auth->getGroups();
        $groupId = $group[0]["group_id"];
        //通用sql
        $sql = 'SUM(amount) AS amount,DATE_FORMAT(FROM_UNIXTIME(datatime), "' . $format . '") AS field_time';
        $category = [];
        $data = [];
        if ($groupId == 1) {
            $amount = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        } else if ($groupId == 2) {
            $amount = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where(['h_id' => $admin["home_id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        } else if ($groupId == 3) {
            $amount = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where(['u_id' => $admin["id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        }
        $category[] = '收入';
        $data[] = [
            'value' => $amount,
            'name' => '收入'
        ];
        if ($groupId == 1) {
            $amount = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        } else if ($groupId == 2) {
            $amount = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where(['h_id' => $admin["home_id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        } else if ($groupId == 3) {
            $amount = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where(['u_id' => $admin["id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")->sum('amount');
        }
        $category[] = '支出';
        $data[] = [
            'value' => $amount,
            'name' => '支出'
        ];
        //组装数据
        $result = [
            'category' => $category,
            'data' => $data,
            'id' => '2',
            'unit' => '元',
            'chart_type' => 'pie',
            'title' => '收支对比',
            'subtext' => '收入与支出对比'
        ];
        return $result;
    }

    //收入与支出
    private function incomesAndPending($endtime, $starttime, $totalseconds, $format)
    {
        //通用sql
        $sql = 'SUM(amount) AS amount,DATE_FORMAT(FROM_UNIXTIME(datatime), "' . $format . '") AS field_time';
        $admin = $this->auth->getUserInfo();
        $group = $this->auth->getGroups();
        $groupId = $group[0]["group_id"];
        if ($groupId == 1) {
            //收入
            $income = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
            //支出
            $spending = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
        } else if ($groupId == 2) {
            //收入
            $income = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where(['h_id' => $admin["home_id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
            //支出
            $spending = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where(['h_id' => $admin["home_id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
        } else if ($groupId == 3) {
            //收入
            $income = \think\Db::name('finance_income_log')
                ->where(['status' => 'audited'])
                ->where(['u_id' => $admin["id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
            //支出
            $spending = \think\Db::name('finance_spending_log')
                ->where(['status' => 'audited'])
                ->where(['u_id' => $admin["id"]])
                ->where('datatime', 'between time', [$starttime, $endtime])
                ->field("{$sql}")
                ->group('field_time')
                ->select();
        }
        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }
        $datalist = array_fill_keys($column, 0);
        foreach ($income as $k => $v) {
            $datalist[$v['field_time']] = isset($datalist[$v['field_time']]) ? round($v['amount'], 2) : 0;
        }
        $series[] = [
            'name' => '收入',
            'type' => 'line',
            'data' => array_values($datalist),
            'markPoint' => [
                'data' => [
                    ['type' => 'max', 'name' => '最大值'],
                    ['type' => 'min', 'name' => '最小值']
                ]
            ],
            'markLine' => [
                'data' => [
                    ['type' => 'average', 'name' => '平均值']
                ]
            ]
        ];

        $datalist = array_fill_keys($column, 0);
        foreach ($spending as $k => $v) {
            $datalist[$v['field_time']] = isset($datalist[$v['field_time']]) ? round($v['amount'], 2) : 0;
        }
        $series[] = [
            'name' => '支出',
            'type' => 'line',
            'data' => array_values($datalist),
            'smooth' => true,
            'markPoint' => [
                'data' => [
                    ['type' => 'max', 'name' => '最大值'],
                    ['type' => 'min', 'name' => '最小值']
                ]
            ],
            'markLine' => [
                'data' => [
                    ['type' => 'average', 'name' => '平均值']
                ]
            ]
        ];

        return [
            'category' => array_keys($datalist), //日期列表
            'data' => [],
            'series' => $series,
            'id' => '1',
            'unit' => '元',
            'legend_title' => ['收入', '支出'],
            'chart_type' => 'graph',
            'title' => '收支趋势',
            'subtext' => '收入和支出趋势图'
        ];
    }
}
